<script setup lang="ts">
import {
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NDatePicker,
  NModal,
  NForm,
  NFormItem,
  NSelect
} from 'naive-ui'
import { onActivated, onMounted, reactive, ref, h, watch, onDeactivated } from 'vue'
import { sendRequest } from '@/utils/api'
import type { clueModel } from '@/api/clue'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute, useRouter } from 'vue-router'

const message = useMessage()
const router = useRouter()
const listOption = ref([])
onActivated(() => {
  if (window.flags.flushRole) {
    queryTableData(true)
    window.flags.flushRole = false
  }
})

const tableData = ref<clueModel[]>([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
type Reset = () => void
function useQueryForm<T = unknown>(form: T, reset: Reset): [form: T, reset: Reset] {
  return [form, reset]
}
const modalVisible = ref(false)
const route = useRoute()
const [form, resetForm] = useQueryForm(
  reactive({
    statusCode: null,
    transferUser: null,
    receiveUser: null,
    collectionConcatUser: null,
    startTime: null,
    endTime: null,
    clueName: null
  }),
  () => {
    form.receiveUser = null
    form.statusCode = null
    form.startTime = null
    form.endTime = null
    form.transferUser = null
    form.collectionConcatUser = null
    form.clueName = null
    timeRange.value = null
  }
)
// 1
const columns: DataTableColumns<clueModel> = [
  {
    title: '线索编号',
    key: 'clueNumber',
    width: '15rem',
    align: 'center'
  },
  {
    title: '线索名称',
    key: 'clueName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '线索状态',
    key: 'statusName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '联系方式',
    key: 'concatUserPhone',
    width: '10rem',
    align: 'center'
  },
  {
    title: '线索提供时间',
    key: 'provideTime',
    width: '10rem',
    align: 'center'
  },
  {
    title: '线索提供方式',
    key: 'provideType',
    width: '10rem',
    align: 'center'
  },
  {
    title: '征集部对接人',
    key: 'collectionConcatUser',
    width: '10rem',
    align: 'center'
  },
  {
    title: '修改时间',
    key: 'updatedTime',
    width: '10rem',
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    width: '20rem',
    align: 'center',
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleEdit(e),
          style: {
            display: !e.editFlag ? 'inline-block' : 'none'
          }
        },
        {
          default: () => '编辑'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleDetail(e)
        },
        {
          default: () => '详情'
        }
      ),
      h(
        NButton,
        {
          type: 'error',
          quaternary: true,
          onClick: () => handleDelete(e.id),
          style: {
            display: e.statusName === '已确认' ? 'none' : 'inline-block'
          }
        },
        {
          default: () => '删除'
        }
      )
    ]
  }
]
const tableLoading = ref(false)
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<clueModel>>({
    module: 'clue',
    api: 'listNew',
    override: {
      params: {
        statusCode: form.statusCode,
        transferUser: form.transferUser,
        receiveUser: form.receiveUser,
        startTime: form.startTime,
        endTime: form.endTime,
        collectionConcatUser: form.collectionConcatUser,
        clueName: form.clueName,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value = res.data.list
}
//下拉
const getFunction = async () => {
  listOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A62'
      }
    }
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listOption.value.push({ label: i.dicName, value: i.dicCode })
  })
}
const handleEdit = (e: any) => {
  router.push({
    name: 'clueManagementClueOrganization',
    params: { id: e.id },
    query: {
      redirect: route.fullPath
    }
  })
}
const handleDetail = (e: any) => {
  router.push({
    name: 'clueManagementDetail',
    params: { id: e.id },
    query: {
      redirect: route.fullPath
    }
  })
}
const handleAdd = () => {
  router.push({
    name: 'clueManagementAdd',
    query: {
      redirect: route.fullPath
    }
  })
}
const ids = ref()
const handleDelete = (id: any) => {
  ids.value = id
  modalVisible.value = true
}
const againDelete = async () => {
  const [error] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'deleteNew',
    override: {
      data: [ids.value]
    }
  })
  if (error) return message.error(error.message)
  queryTableData(true)
  modalVisible.value = false
}
const isAdd = ref(false)
const queryCheckUserInZjb = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'collectNotice',
    api: 'checkUserInZjb'
  })
  if (error) return message.error(error.message)
  isAdd.value = res.data
}
//日期选择器
const timeRange = ref()
const changeTime = (e: any) => {
  if (e) {
    form.startTime = e[0]
    form.endTime = e[1]
  } else {
    form.startTime = null
    form.endTime = null
  }
}
onMounted(() => {
  getFunction()
  queryCheckUserInZjb()
  queryTableData(true)
})
const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))
watch(
  () => route,
  () => {
    if (route.path == '/collectionManagement/collectionProcess/clueManagement/index') {
      queryTableData(true)
      window.addEventListener('keyup', keyUpDown, false) // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="role">
    <template #form>
      <NForm
        :show-feedback="false"
        label-placement="left"
        inline
      >
        <span style="line-height: 34px">线索名称：</span>
        <NInput
          placeholder="输入线索名称"
          v-model:value="form.clueName"
          style="width: 200px; margin-right: 20px"
        />
        <span style="line-height: 34px">征集部对接人：</span>
        <NInput
          placeholder="输入征集部对接人"
          v-model:value="form.collectionConcatUser"
          style="width: 200px; margin-right: 20px"
        />
        <span style="line-height: 34px">线索状态：</span>
        <NSelect
          :options="listOption"
          v-model:value="form.statusCode"
          placeholder="请选择状态"
          clearable
          style="width: 200px; margin-right: 20px"
        />
        <span style="line-height: 34px">线索提供时间：</span>
        <NDatePicker
          input-readonly
          type="datetimerange"
          default-time="00:00:00"
          clearable
          v-model:value="timeRange"
          value-format="yyyy-MM-dd HH:mm:ss"
          :on-update:formatted-value="changeTime"
          style="margin-right: 20px"
        />
        <NFormItem></NFormItem>
        <NButton
          type="primary"
          style="width: 78px; margin-right: 10px"
          ghost
          @click="queryTableData(true)"
          :loading="tableLoading"
        >
          查询
        </NButton>
        <NButton
          type="primary"
          ghost
          style="width: 78px; margin-right: 10px"
          @click="resetForm"
        >
          重置
        </NButton>
      </NForm>
      <NSpace>
        <NSpace align="end">
          <NButton
            type="primary"
            style="width: 115px"
            @click="handleAdd"
            v-if="isAdd"
          >
            新增
          </NButton>
        </NSpace>
      </NSpace>
    </template>
    <template #table="props">
      <NDataTable
        v-bind="props"
        :data="tableData"
        :columns="columns"
        :loading="tableLoading"
        size="small"
        :bordered="false"
      />
    </template>
    <template #pagination>
      <NPagination
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker
        show-quick-jumper
        :suffix="() => '页'"
      >
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
  >
    <VDialogContent
      @close="modalVisible = false"
      @submit="againDelete"
      title="删除提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<style lang="scss" scoped>
.role {
  padding: 29rem 20rem 42rem 30rem;
  color: rgba(0, 0, 0, 0.85);
}
</style>
